<template>
  <div>
    <el-page-header @back="$router.back()" title="文档上传" content="上传新文档到系统" />
    
    <el-card style="margin-top: 20px;">
      <el-form ref="uploadFormRef" :model="documentInfo" :rules="rules" label-width="100px">
        <!-- 文件上传 -->
        <el-form-item label="选择文件" prop="files">
          <el-upload
            ref="uploadRef"
            v-model:file-list="fileList"
            :auto-upload="false"
            :show-file-list="true"
            :multiple="true"
            accept=".pdf,.doc,.docx,.txt,.md,.ppt,.pptx,.xls,.xlsx"
            drag
            @change="handleFileChange"
            @remove="handleFileRemove"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖拽到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持格式: PDF, Word, TXT, Markdown, PPT, Excel 等，单个文件不超过100MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 文档信息 -->
        <el-form-item label="文档标题" prop="title">
          <el-input 
            v-model="documentInfo.title" 
            placeholder="请输入文档标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="文档描述">
          <el-input 
            v-model="documentInfo.description" 
            type="textarea"
            placeholder="请输入文档描述"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="文档标签">
          <el-select
            v-model="documentInfo.tags"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入标签"
            style="width: 100%;"
          >
            <el-option
              v-for="tag in predefinedTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="文档类别">
          <el-select v-model="documentInfo.category" placeholder="请选择文档类别" style="width: 100%;">
            <el-option label="技术文档" value="technical" />
            <el-option label="用户手册" value="manual" />
            <el-option label="API文档" value="api" />
            <el-option label="业务文档" value="business" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="访问权限">
          <el-radio-group v-model="documentInfo.visibility">
            <el-radio label="public">公开</el-radio>
            <el-radio label="private">私有</el-radio>
            <el-radio label="restricted">受限</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="启用向量化">
          <el-switch 
            v-model="documentInfo.enableVectorization"
            active-text="是"
            inactive-text="否"
          />
          <div style="margin-top: 8px; color: #909399; font-size: 12px;">
            启用后文档将被向量化用于智能搜索和问答
          </div>
        </el-form-item>

        <!-- 上传进度 -->
        <div v-if="uploadProgress.show" style="margin-bottom: 20px;">
          <el-alert
            :title="`上传进度: ${uploadProgress.percent}%`"
            type="info"
            :closable="false"
          >
            <el-progress
              :percentage="uploadProgress.percent"
              :status="uploadProgress.status"
            />
            <div style="margin-top: 8px; color: #666;">
              {{ uploadProgress.message }}
            </div>
          </el-alert>
        </div>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleUpload" 
            :loading="uploading"
            :disabled="fileList.length === 0"
          >
            {{ uploading ? '上传中...' : '开始上传' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { documentApi } from '@/api'
import { useRouter } from 'vue-router'

const router = useRouter()
const uploadFormRef = ref()
const uploadRef = ref()

const fileList = ref([])
const uploading = ref(false)

const documentInfo = ref({
  title: '',
  description: '',
  tags: [],
  category: '',
  visibility: 'public',
  enableVectorization: true
})

const uploadProgress = ref({
  show: false,
  percent: 0,
  status: '',
  message: ''
})

const predefinedTags = ['技术', '文档', 'API', '手册', '教程', '规范', '指南']

const rules = {
  title: [
    { required: true, message: '请输入文档标题', trigger: 'blur' },
    { min: 2, message: '标题至少2个字符', trigger: 'blur' }
  ],
  files: [
    { 
      validator: (rule, value, callback) => {
        if (fileList.value.length === 0) {
          callback(new Error('请选择要上传的文件'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 处理文件变化
const handleFileChange = (file, files) => {
  // 验证文件大小
  if (file.raw && file.raw.size > 100 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过100MB')
    files.splice(files.indexOf(file), 1)
    return
  }
  
  // 如果没有设置标题，使用第一个文件名作为标题
  if (!documentInfo.value.title && files.length === 1) {
    const fileName = file.name
    const title = fileName.substring(0, fileName.lastIndexOf('.')) || fileName
    documentInfo.value.title = title
  }
}

// 处理文件移除
const handleFileRemove = (file, files) => {
  fileList.value = files
}

// 上传文件
const handleUpload = async () => {
  try {
    const valid = await uploadFormRef.value.validate()
    if (!valid) return

    if (fileList.value.length === 0) {
      ElMessage.error('请选择要上传的文件')
      return
    }

    uploading.value = true
    uploadProgress.value = {
      show: true,
      percent: 0,
      status: 'active',
      message: '准备上传文件...'
    }

    // 逐个上传文件
    for (let i = 0; i < fileList.value.length; i++) {
      const file = fileList.value[i]
      
      uploadProgress.value.message = `正在上传文件 ${i + 1}/${fileList.value.length}: ${file.name}`
      
      const formData = new FormData()
      formData.append('file', file.raw)
      formData.append('title', documentInfo.value.title)
      formData.append('description', documentInfo.value.description || '')
      formData.append('tags', JSON.stringify(documentInfo.value.tags))
      formData.append('category', documentInfo.value.category || '')
      formData.append('visibility', documentInfo.value.visibility)
      formData.append('enableVectorization', documentInfo.value.enableVectorization)

      await documentApi.uploadDocument(formData, {
        onUploadProgress: (progressEvent) => {
          const fileProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          const totalProgress = Math.round(((i + fileProgress / 100) * 100) / fileList.value.length)
          uploadProgress.value.percent = totalProgress
        }
      })
    }

    uploadProgress.value.status = 'success'
    uploadProgress.value.message = '所有文件上传完成！'
    uploadProgress.value.percent = 100

    ElMessage.success('文档上传成功！')
    
    // 重置表单
    resetForm()
    
    // 3秒后跳转到文档列表
    setTimeout(() => {
      router.push('/documents')
    }, 3000)

  } catch (error) {
    console.error('上传失败:', error)
    uploadProgress.value.status = 'exception'
    uploadProgress.value.message = '上传失败: ' + (error.response?.data?.message || error.message)
    ElMessage.error('文档上传失败')
  } finally {
    uploading.value = false
    // 5秒后隐藏进度条
    setTimeout(() => {
      uploadProgress.value.show = false
    }, 5000)
  }
}

// 重置表单
const resetForm = () => {
  uploadFormRef.value?.resetFields()
  fileList.value = []
  documentInfo.value = {
    title: '',
    description: '',
    tags: [],
    category: '',
    visibility: 'public',
    enableVectorization: true
  }
  uploadProgress.value = {
    show: false,
    percent: 0,
    status: '',
    message: ''
  }
}
</script>
